part of quadcoptershared;
 
int boundsChange = 100;

int last_version = 1;
int getNextVersion() { return last_version++; }

 // Does all the work 
 // can serialize and (I hope) run in
 // server and Browser
class QuadCopterManager {
   int version;
   Map<String,QuadCopter> copters;
  
  // current position 
  // different on each call
  void updateCopter(QuadCopter added)
  {
    copters[added.id] = added;
    version = getNextVersion();
  }
  
  // Named constructor - takes object name
  QuadCopterManager(  )   
  {
    version = getNextVersion();
    copters = new Map();
   }
  
  
  void addCopter(QuadCopter copter) {
    copters[copter.id] = copter;
      
  }
 
    
  Map toJson() {
    return {
      "version": version,
      "copters": json.stringify(copters),
     };
  }


  // Equals does not work
  // this tolerates roundoff
  bool isEquivalent(QuadCopterManager o)
  {
    if(version != o.version)
      return false;
    if(copters.length != o.copters.length)
      return false;
    for(String id in copters.keys) {
       if(!copters[id].isEquivalent(o.copters[id]))
         return false;
    }
       
     return true;
  }
  
  // Named constructor
  // 
  QuadCopterManager.fromJson(Map mp) {
    version = mp['version'];
    copters = json.parse( mp['copters']);
  }
  
   Iterable<String> copterIds() {
    return copters.keys;
  }
  
   QuadCopter getCopter(String id) {
     return copters[id];
   }
   
   /**
    * return a coy of the copters
    */
   Map getCopterMap() {
      Map copy = new Map();
      copy.addAll(copters);
      return copy;
   }
  
  /**
   * Returns the value for the given [key] or null if [key] is not
   * in the map. Because null values are supported, one should either
   * use [containsKey] to distinguish between an absent key and a null
   * value, or use the [putIfAbsent] method.
   */
  QuadCopter operator [](String id) {
    return copters[id];
  }
  /**
   * Applies [f] to each {key, value} pair of the map.
   *
   * It is an error to add or remove keys from the map during iteration.
   */
  void forEach(void f( QuadCopter value)) {
     for (String key in copters.keys)
         f(copters[key]);
  }
  
}

